package com.rabc.framework.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.exception.user.UserException;
import com.exception.user.UserPasswordNotMatchException;
import com.rabc.framework.web.domain.LoginUserDetails;
import com.rabc.web.entity.SysUser;
import com.rabc.web.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService userService;


    /**
     * 加载数据库中的用户信息到权限框架上下文中
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)  throws  UsernameNotFoundException{
        SysUser loginUser = userService.getOne(new QueryWrapper<SysUser>().eq("user_name", username));
        if (loginUser == null) {
            log.info("用户: {} 不存在", username);
            throw  new UsernameNotFoundException("用户不存在");
        }
        log.info("用户: {} 加载成功", username);
        return createUserDetails(loginUser.getUserName(), loginUser.getPassword(), loginUser);


    }

    private UserDetails createUserDetails(String username, String password, SysUser sysUser) {
        LoginUserDetails userDetails = new LoginUserDetails(sysUser);
        return userDetails;
    }
}
